package com.swgk.core.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.makeramen.roundedimageview.RoundedImageView;
import com.swgk.core.R;

import org.jetbrains.annotations.NotNull;
import org.xmlpull.v1.XmlPullParser;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * @author: 王彬臣
 * @date: 2021/7/20
 * @Description: html富文本解析
 */
public class HtmlParserUtils {
    String p_tag = "";
    List<String> urls;
    Context mContext;

    public HtmlParserUtils(Context mContext) {
        this.mContext = mContext;
    }
    //解析html
    public  void addDetailFromXML(String content, LinearLayout view) {

        ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes());
        getUrls(bais);

        ByteArrayInputStream baisa = new ByteArrayInputStream(content.getBytes());
        readXML(baisa, view);
    }



    //获取全部图片urls
    public void getUrls(InputStream inStream) {
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(inStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        urls = new ArrayList<String>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase("img")) {
                            urls.add(parser.getAttributeValue(null, "src").toString());
                            eventType = parser.next();
                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件

                        break;
                }
                eventType = parser.next();
            }
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 读取XML
    public void readXML(InputStream inStream, LinearLayout article_new_content) {
        XmlPullParser parser = Xml.newPullParser();
        HashMap<String, String> params = new HashMap<String, String>();
        try {
            parser.setInput(inStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        break;
                    case XmlPullParser.TEXT:
                        params.clear();
                        params.put("tag", "p");
                        if (!"".equals(p_tag)) {
                            params.put("strong", "true");
                            p_tag = "";
                        }
                        try {
                            params.put("txt", parser.getText());
                            article_new_content.addView(getLayoutItem(params, mContext));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        params.clear();
                        if (name.equalsIgnoreCase("p")) {

                        } else if (name.equalsIgnoreCase("h2")) {
                            params.put("tag", "h2");
                            params.put("txt", parser.nextText());
                            article_new_content.addView(getLayoutItem(params, mContext));
                        } else if (name.equalsIgnoreCase("img")) {
                            params.put("tag", "img");
                            params.put("src", parser.getAttributeValue(null, "src"));
                            params.put("height", parser.getAttributeValue(null, "height"));
                            params.put("width", parser.getAttributeValue(null, "width"));
                            article_new_content.addView(getLayoutItem(params, mContext));
                        } else if (name.equalsIgnoreCase("strong")) {

                            p_tag = "strong";
                        }
                        break;

                    case XmlPullParser.END_TAG:// 结束元素事件

                        break;
                }

                eventType = parser.next();
            }

            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public View getLayoutItem(HashMap<String, String> params, final Context mcContext) {
        RequestOptions options = new RequestOptions()
                .placeholder(com.swgk.core.R.drawable.null_img_list)//图片加载出来前，显示的图片
                .error(com.swgk.core.R.drawable.null_img_list);//图片加载失败后，显示的图片
        String tag = params.get("tag");
        if (tag.startsWith("p")) {
            TextView tv = new TextView(mcContext);
            String text = params.get("txt");
            tv.setText(text);
            if (params.get("strong") != null) {
                tv.setTextColor(Color.parseColor("#000000"));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, mcContext.getResources().getDimension(com.swgk.core.R.dimen.dp14));

                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD ));
            } else {

                //   tv.setPadding(0, DisplayUtil.dip2px(mContext, 8), 0, DisplayUtil.dip2px(mContext, 8));
                tv.setTextColor(Color.parseColor("#000000"));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, mcContext.getResources().getDimension(com.swgk.core.R.dimen.dp14));
                // tv.setLineSpacing(DisplayUtil.dip2px(mContext, 4), 1);
            }
            return tv;

        }
        if (tag.startsWith("h2")) {
            TextView tv = new TextView(mcContext);
            //   tv.setPadding(0, DisplayUtil.dip2px(mContext, 15), 0, DisplayUtil.dip2px(mContext, 15));
            String text = params.get("txt");
            // tv.setLineSpacing(DisplayUtil.dip2px(mContext, 4), 1);
            tv.setText(text);
            tv.setTextColor(Color.parseColor("#000000"));
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, mcContext.getResources().getDimension(com.swgk.core.R.dimen.dp14));
            return tv;
        } else if (tag.startsWith("img")) {
            String src = params.get("src");
            String width = params.get("width");
            String height = params.get("height");
            if ("".equals(src) || src == null) {
                TextView tv = new TextView(mcContext);
                tv.setText("");
                return tv;
            }
            final RoundedImageView imageView = new RoundedImageView(mContext);
            imageView.setCornerRadius(DisplayUtil.dip2px(mContext, 2));
            imageView.setOval(false);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (height == null) {
                final int  s_w = mcContext.getResources().getDisplayMetrics().widthPixels;
                //获取图片真正的宽高
                Glide.with(mcContext)
                        .asBitmap() //强制Glide返回一个Bitmap对象
                        .load(src+"")
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull @NotNull Bitmap bitmap, @Nullable @org.jetbrains.annotations.Nullable Transition<? super Bitmap> transition) {
                                int imageWidth = bitmap.getWidth();
                                int imageHeight = bitmap.getHeight();
                                int s_h = imageHeight * s_w / imageWidth;
                                LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, s_h);
                                llp.topMargin=DisplayUtil.dip2px(mContext, 10);
                                imageView.setLayoutParams(llp);

                            }
                        });

                Glide.with(mContext).load(src).apply(options).into(imageView);
                return imageView;
            }
            try {
                float h = Float.parseFloat(height);
                float w = Float.parseFloat(width);
                float s_w = mcContext.getResources().getDisplayMetrics().widthPixels;
                float s_h = h * s_w / w;

                LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        (int) s_h);
                imageView.setLayoutParams(llp);
                llp.topMargin = DisplayUtil.dip2px(mContext, 10);
                Glide.with(mContext).load(src).apply(options).into(imageView);



            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return imageView;
        }
        TextView tv = new TextView(mcContext);
        tv.setText("");
        return tv;
    }
}
